<template>
  <div class="menu-management-container">
    <!-- 搜索区域 -->
    <el-card shadow="never" class="search-card">
      <el-form :inline="true" :model="queryData" class="search-form">
        <el-form-item label="菜单名称">
          <el-input v-model="queryData.title" placeholder="请输入菜单名称" clearable />
        </el-form-item>
        <el-form-item label="菜单路径">
          <el-input v-model="queryData.path" placeholder="请输入菜单路径" clearable />
        </el-form-item>
        <el-form-item>
          <ElButton type="primary" :icon="Search" @click="searchMenu">查询</ElButton>
          <ElButton @click="resetSearch" :icon="Refresh">重置</ElButton>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 标题和操作区域 -->
    <div class="header">
      <div class="actions">
        <el-button type="primary" @click="createHandle" :icon="Plus">新增菜单</el-button>
        <el-button type="success" @click="refreshMenu" :icon="Refresh">刷新菜单</el-button>
      </div>
    </div>

    <!-- 菜单表格 -->
    <el-table 
      :data="processedMenuData" 
      row-key="path" 
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" 
      border 
      stripe
      style="width: 100%" 
      v-loading="loading" 
      class="menu-table" 
      height="calc(100vh - 280px)"
      default-expand-all
    >
      <el-table-column type="index" width="50" align="center" />
      <el-table-column prop="meta.title" label="菜单名称" align="center" min-width="80" />
      <el-table-column label="菜单图标" min-width="80" align="center">
        <template #default="{ row }">
          <TIcon v-if="row.meta.icon" :icon="row.meta.icon" />
          <span v-else>—</span>
        </template>
      </el-table-column>
      <el-table-column label="菜单类型" min-width="80" align="center">
        <template #default="{ row }">
          <el-tag :type="getMenuTypeTagType(row)" size="small"  effect="dark">
            {{ getMenuTypeText(row) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="路由名" min-width="150" />
      <el-table-column prop="path" label="菜单路径" min-width="180" />
      <el-table-column prop="component" label="组件路径" min-width="180" />
      <el-table-column label="排序" min-width="60" align="center">
        <template #default="{ row }">
          {{ row.sortOrder || 0 }}
        </template>
      </el-table-column>
      <el-table-column label="状态" min-width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="row.isActive === 'Y' ? 'success' : 'danger'"  effect="dark" size="small">
            {{ row.isActive === 'Y' ? '激活' : '失效' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" min-width="120" align="center">
        <template #default="{ row }">
          <el-button size="small" type="success" :icon="Plus" @click="handleAdd(row)" text title="添加子项" />
          <el-button size="small" type="primary" :icon="Edit" text title="编辑" @click="edit(row)" />
          <el-button size="small" type="danger" :icon="Delete" text title="删除" @click="handleDelete(row)" />
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="880px" draggable :close-on-click-modal="false"
      class="menu-dialog">
      <el-form ref="formRef" :model="currentMenu" :rules="formRules" label-width="110px" label-position="right"
        class="spaced-form">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="上级菜单" prop="parentId">
              <el-cascader 
                v-model="currentMenu.parentId" 
                :options="menuOptions" 
                :props="{
                  checkStrictly: true,
                  emitPath: false,
                  children: 'children',
                  label: 'label',
                  value: 'value'
                }" 
                :show-all-levels="false" 
                placeholder="请选择上级菜单" 
                style="width: 100%" 
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单类型" prop="menuType">
              <el-radio-group v-model="currentMenu.menuType" @change="menuTypeChange">
                <el-radio label="M">目录</el-radio>
                <el-radio label="C">菜单</el-radio>
            
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="菜单名称" prop="title">
              <el-input v-model="currentMenu.title" placeholder="请输入菜单名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="sortOrder">
              <el-input-number v-model="currentMenu.sortOrder" :min="0" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="菜单图标">
              <el-select v-model="currentMenu.icon" placeholder="请选择图标" style="width: 100%">
                <el-option v-for="icon in iconOptions" :key="icon" :value="icon" :label="icon">
                  <div style="display: flex; align-items: center">
                    <TIcon :icon="icon" style="margin-right: 8px" />
                    <span>{{ icon }}</span>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="路由名称" prop="name">
              <el-input v-model="currentMenu.name" placeholder="请输入路由名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否隐藏">
              <el-radio-group v-model="currentMenu.isHide">
                <el-radio :label="true">隐藏</el-radio>
                <el-radio :label="false">显示</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否外链">
              <el-radio-group v-model="currentMenu.isShowLink" @change="toggleLinkField">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否全屏">
              <el-radio-group v-model="currentMenu.isFull">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否固定">
              <el-radio-group v-model="currentMenu.isAffix">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否缓存">
              <el-radio-group v-model="currentMenu.isKeepAlive">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="currentMenu.isActive">
                <el-radio label="Y">激活</el-radio>
                <el-radio label="N">失效</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item v-if="currentMenu.isShowLink" label="外链地址" prop="isLink">
              <el-input v-model="currentMenu.isLink" placeholder="请输入外链地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="高亮菜单">
              <el-input v-model="currentMenu.activeMenu" placeholder="请输入高亮菜单" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="路由地址" prop="path">
              <el-input v-model="currentMenu.path" placeholder="请输入路由地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="currentMenu.menuType === 'C'" label="组件路径" prop="component">
              <el-input v-model="currentMenu.component" placeholder="请输入组件路径" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="重定向地址">
          <el-input v-model="currentMenu.redirect" placeholder="请输入重定向地址" />
        </el-form-item>

        <el-form-item label="备注">
          <el-input v-model="currentMenu.remark" type="textarea" :rows="2" placeholder="请输入备注" />
        </el-form-item>
        
        <!-- 功能按钮管理区域（仅在菜单类型为'C'时显示） -->
        <div v-if="currentMenu.menuType === 'C'">
          <el-divider>功能按钮管理</el-divider>
          <div class="button-management">
            <div class="button-header">
              <span class="section-title">功能按钮</span>
              <div class="button-actions">
                <el-button type="primary" size="small" @click="addNewButton" :icon="Plus">添加</el-button>
                <el-button type="success" size="small" @click="saveButtons" :icon="Check">保存</el-button>
                <el-button type="danger" size="small" @click="removeSelectedButtons" :icon="Delete">删除</el-button>
              </div>
            </div>

            <el-table :data="currentMenu.functionButtons" border style="width: 100%"
              @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column prop="name" label="按钮名称" min-width="150">
                <template #default="{ row }">
                  <el-input v-model="row.name" placeholder="请输入按钮名称" />
                </template>
              </el-table-column>
              <el-table-column prop="code" label="按钮编码" min-width="150">
                <template #default="{ row }">
                  <el-input v-model="row.code" placeholder="请输入按钮编码" />
                </template>
              </el-table-column>
              <el-table-column prop="description" label="描述" min-width="200">
                <template #default="{ row }">
                  <el-input v-model="row.description" type="textarea" autosize placeholder="请输入描述" />
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addConfirm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { type FormInstance, type FormRules } from 'element-plus';
import { Plus, Edit, Delete, Setting, Search, Refresh, Check } from '@element-plus/icons-vue';
import type { MenuOptions } from './type';
import TIcon from './icon.vue';
import { useAuthStore } from '@/stores/module/auth';
import { GetMenusList, AddMenu, EditMenu, DeleteMenus } from '@/api/system/menu';

// 权限管理
const authStore = useAuthStore();
const btnPermissions = ref<string[]>(authStore.authButtonListGet || []);

// 图标选项
const iconOptions = [
  'HomeFilled',
  'List',
  'Lock',
  'Tools',
  'User',
  'Grid',
  'Menu',
  'DataLine',
  'SetUp',
  'Operation'
];

// 查询条件
const queryData = reactive({
  title: '',
  path: ''
});

// 菜单数据
const processedMenuData = ref<MenuOptions[]>([]);
const loading = ref(false);

const selectedButtons = ref<any[]>([]);
// 菜单树形数据
const menuOptions = ref<MenuOptions[]>([]);

// 弹窗状态
const dialogVisible = ref(false);
const dialogTitle = ref('新增菜单');
const formRef = ref<FormInstance>();

// 当前菜单
const currentMenu = reactive({
  id: 0,
  menuId: 0,
  parentId: 0,
  menuType: 'M' as 'M' | 'C' | 'B',
  title: '',
  sortOrder: 0,
  icon: '',
  isShowLink: false,
  isLink: '',
  isHide: false,
  isFull: false,
  isAffix: false,
  isActive: 'Y',
  isKeepAlive: false,
  activeMenu: '',
  path: '',
  name: '',
  component: '',
  redirect: '',
  remark: '',
  functionButtons: [] as any[] // 存储功能按钮
});

// 表单验证规则
const formRules: FormRules = {
  title: [
    { required: true, message: '菜单名称不能为空', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在2到20个字符', trigger: 'blur' }
  ],
  sortOrder: [
    { required: true, message: '请输入显示排序', trigger: 'blur' }
  ],
  path: [
    { required: true, message: '路由路径不能为空', trigger: 'blur' },
    {
      pattern: /^\/[a-zA-Z0-9/-]+$/,
      message: '路径格式不正确，应以/开头',
      trigger: 'blur'
    }
  ],
  component: [
    { required: true, message: '组件路径不能为空', trigger: 'blur' }
  ],
  isLink: [
    { required: true, message: '请输入外链地址', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '路由名称不能为空', trigger: 'blur' }
  ],
  menuType: [
    { required: true, message: '请选择菜单类型', trigger: 'change' }
  ]
};

// 获取菜单类型标签样式
const getMenuTypeTagType = (row: MenuOptions) => {
  if (row.menuType === 'M') return 'info';
  if (row.menuType === 'C') return 'success';
  return 'warning';
};

// 获取菜单类型文本
const getMenuTypeText = (row: MenuOptions) => {
  if (row.menuType === 'M') return '目录';
  if (row.menuType === 'C') return '菜单';
  return '按钮';
};

// 搜索菜单
const searchMenu = () => {
  getMenuData();
};

// 重置搜索
const resetSearch = () => {
  queryData.title = '';
  queryData.path = '';
  getMenuData();
};

// 刷新菜单
const refreshMenu = () => {
  getMenuData();
  ElMessage.success('菜单已刷新');
};

// 添加子菜单
const handleAdd = (parent: MenuOptions) => {
  dialogTitle.value = '添加子菜单';
  resetForm();
  currentMenu.parentId = parent.Id || parent.menuId;
  dialogVisible.value = true;
};

// 编辑菜单
const edit = (row: MenuOptions) => {
  dialogTitle.value = '编辑菜单';
  resetForm();

  Object.assign(currentMenu, {
    id: row.Id || row.menuId,
    menuId: row.Id || row.menuId,
    parentId: row.parentId || 0,
    menuType: row.menuType || 'M',
    title: row.meta.title,
    sortOrder: row.sortOrder || 0,
    icon: row.meta.icon,
    isShowLink: !!row.meta.isLink,
    isLink: row.meta.isLink || '',
    isHide: row.meta.isHide,
    isFull: row.meta.isFull,
    isAffix: row.meta.isAffix,
    isActive: row.isActive || 'Y',
    isKeepAlive: row.meta.isKeepAlive,
    activeMenu: row.meta.activeMenu || '',
    path: row.path,
    name: row.name,
    component: row.component,
    redirect: row.redirect || '',
    remark: row.remark || '',
    functionButtons: row.functionButtons || [] // 加载功能按钮
  });

  dialogVisible.value = true;
};

// 删除菜单
const handleDelete = async (target: MenuOptions) => {
  try {
    await ElMessageBox.confirm('确定要删除该菜单吗？删除后不可恢复！', '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    loading.value = true;
    const res = await DeleteMenus([String(target.Id || target.menuId)]);
    if (res.Code === 200) {
      ElMessage.success(res.Msg);
    } else {
      ElMessage.error(res.Msg);
    }

    getMenuData();
  } catch (error) {
    // 用户取消删除
  } finally {
    loading.value = false;
  }
};

// 新增菜单
const createHandle = () => {
  dialogTitle.value = '新增菜单';
  resetForm();
  dialogVisible.value = true;
};

// 重置表单
const resetForm = () => {
  Object.assign(currentMenu, {
    id: 0,
    menuId: 0,
    parentId: 0,
    menuType: 'M',
    title: '',
    sortOrder: 0,
    icon: '',
    isShowLink: false,
    isLink: '',
    isHide: false,
    isFull: false,
    isAffix: false,
    isActive: 'Y',
    isKeepAlive: false,
    activeMenu: '',
    path: '',
    name: '',
    component: '',
    redirect: '',
    remark: '',
    functionButtons: [] // 重置功能按钮
  });

  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 菜单类型变化
const menuTypeChange = (val: string | number | boolean | undefined) => {
  if (typeof val === 'string' && ['M', 'C', 'B'].includes(val)) {
    currentMenu.menuType = val as 'M' | 'C' | 'B';
    if (val === 'M') {
      currentMenu.component = '';
    }
  }
};
// 切换外链字段显示
const toggleLinkField = (val: string | number | boolean | undefined) => {
  if (typeof val === 'boolean') {
    currentMenu.isShowLink = val;
    if (!val) {
      currentMenu.isLink = '';
    }
  }
};

// 处理多选
const handleSelectionChange = (selection: any[]) => {
  selectedButtons.value = selection;
};

// 添加新按钮
const addNewButton = () => {
  currentMenu.functionButtons.push({
    name: '',
    code: '',
    description: ''
  });
};

// 保存所有按钮
const saveButtons = () => {
  // 验证所有按钮
  for (const button of currentMenu.functionButtons) {
    if (!button.name || !button.code) {
      ElMessage.warning('请填写所有按钮的名称和编码');
      return;
    }
  }
  ElMessage.success('按钮已保存');
};

// 删除选中的按钮
const removeSelectedButtons = () => {
  if (selectedButtons.value.length === 0) {
    ElMessage.warning('请选择要删除的按钮');
    return;
  }

  // 过滤掉选中的按钮
  currentMenu.functionButtons = currentMenu.functionButtons.filter(
    button => !selectedButtons.value.includes(button)
  );

  ElMessage.success(`已删除 ${selectedButtons.value.length} 个按钮`);
  selectedButtons.value = [];
};

// 提交表单
const addConfirm = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();

    // 创建符合后端格式的数据对象
    const menuData = {
      Id: currentMenu.id,
      Path: currentMenu.path,
      Name: currentMenu.name,
      Component: currentMenu.component,
      Redirect: currentMenu.redirect || null,
      Icon: currentMenu.icon,
      Title: currentMenu.title,
      IsActive: currentMenu.isActive,
      MenuType: currentMenu.menuType,
      ActiveMenu: currentMenu.activeMenu || null,
      IsLink: currentMenu.isShowLink ? currentMenu.isLink : null,
      IsHide: currentMenu.isHide ? 1 : 0,
      IsFull: currentMenu.isFull ? 1 : 0,
      IsAfix: currentMenu.isAffix ? 1 : 0, // 注意后端字段名是 IsAfix
      IsKeepAlive: currentMenu.isKeepAlive ? 1 : 0,
      ParentId: currentMenu.parentId || 0,
      SortOrder: currentMenu.sortOrder,
      Remark: currentMenu.remark || null,
      FunctionButtons: currentMenu.functionButtons || []
    };

    loading.value = true;
    if (currentMenu.id) {
      const response = await EditMenu(menuData);
      if (response.Code === 200) {
        ElMessage.success(response.Msg || '菜单更新成功');
      } else {
        ElMessage.error(response.Msg || '菜单更新失败');
      }
    } else {
      const response = await AddMenu(menuData);
      if (response.Code === 200) {
        ElMessage.success(response.Msg || '菜单添加成功');
      } else {
        ElMessage.error(response.Msg || '菜单添加失败');
      }
    }

    dialogVisible.value = false;
    getMenuData();
  } catch (error) {
    console.error('表单验证失败或保存错误:', error);
    if (error instanceof Error) {
      ElMessage.error(`操作失败: ${error.message}`);
    } else {
      ElMessage.error('操作失败，请检查表单数据');
    }
  } finally {
    loading.value = false;
  }
};

// 获取菜单数据
const getMenuData = async () => {
  loading.value = true;
  try {
    const response = await GetMenusList();
    if (response.Code === 200) {
      processedMenuData.value = response.Data;
      generateMenuOptions(response.Data);
    } else {
      const msg = response.Msg || '未知错误';
      ElMessage.error(`获取菜单数据失败! ${msg}`);
    }
  } catch (error) {
    ElMessage.error(`获取菜单数据失败! ${error}`);
  } finally {
    loading.value = false;
  }
};

// 生成菜单树选项（确保排序）
const generateMenuOptions = (data: MenuOptions[]) => {
  const options: any[] = [
    {
      value: 0,
      label: '顶级菜单',
      children: []
    }
  ];

  // 递归处理菜单项（确保按SortOrder排序）
  const processMenu = (items: MenuOptions[]) => {
    return items
      .sort((a, b) => (a.sortOrder || 0) - (b.sortOrder || 0))
      .map(item => {
        const menuItem: any = {
          value: item.Id || item.menuId,
          label: item.meta.title,
          children: item.children ? processMenu(item.children) : []
        };
        return menuItem;
      });
  };

  if (data && data.length > 0) {
    options[0].children = processMenu(data);
  }

  menuOptions.value = options;
};

onMounted(() => {
  getMenuData();
});
</script>

<style scoped lang="scss">
.menu-management-container {
  padding: 18px;
  background-color: #f8fafc;
  min-height: calc(100vh - 60px);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 18px 0;
  padding: 0 10px;
}

.search-card {
  margin-bottom: 18px;
  border-radius: 8px;
  background-color: #ffffff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

  .search-form {
    display: flex;
    flex-wrap: wrap;
    align-items: center;

    :deep(.el-form-item) {
      margin-bottom: 0;
      margin-right: 16px;
    }
  }
}

.menu-table {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);

  :deep(.el-table__row) {
    transition: background-color 0.2s;

    &:hover {
      background-color: #f5f9ff;
    }
  }

  :deep(.el-tag) {
    font-weight: 500;
    padding: 0 8px;
    height: 24px;
    line-height: 24px;
  }
}

.menu-dialog {
  .spaced-form {
    padding: 10px 15px;

    .el-form-item {
      margin-bottom: 18px;
    }

    .el-row {
      margin-bottom: 8px;
    }
  }

  .el-dialog__body {
    padding: 20px 25px;
  }

  .el-dialog__footer {
    padding: 15px 25px;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding-top: 15px;
  border-top: 1px solid #eee;
}

.button-management {
  padding: 10px;
  margin-top: 20px;
  border: 1px solid #ebeef5;
  border-radius: 6px;
  background-color: #f8fafc;

  .button-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;

    .section-title {
      font-size: 15px;
      font-weight: 600;
      color: #409eff;
    }
  }

  .button-actions {
    display: flex;
    justify-content: center;
    gap: 8px;
  }
}

@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
    align-items: flex-start;

    :deep(.el-form-item) {
      margin-right: 0;
      margin-bottom: 12px;
      width: 100%;
    }
  }

  .header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;

    .actions {
      width: 100%;
      display: flex;
      justify-content: flex-start;
      gap: 10px;
    }
  }

  .menu-dialog {
    width: 95% !important;
    max-width: 100%;
  }
}
</style>